package top.javahai.subtlechat.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

/**
 * springboot 配置不同的 MongoTemplate
 * @author qiangfanghao
 * @date
 */

@Configuration
public class MongoTemplateConfig {

    @Value("${spring.data.mongodb.major.uri}")
    private String uri;

    @Autowired
    private ApplicationContext appContext;


    @Primary
    @Bean(name = "mongoMajorTemplate")
    public MongoTemplate mongoMajorTemplate() throws Exception {

        return new MongoTemplate(mongoMajorFactory(),mappingMongoConverter(mongoMajorFactory()));
    }

    @Bean
    @Primary
    public MongoDatabaseFactory mongoMajorFactory() throws Exception {
        return new SimpleMongoClientDatabaseFactory(uri);
    }


    /**
     * 使用自定义的typeMapper去除写入mongodb时的“_class”字段
     * @throws Exception
     */
    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDatabaseFactory factory) throws Exception {

        MongoMappingContext mongoMappingContext =new MongoMappingContext();
        mongoMappingContext.setApplicationContext(appContext);

        MappingMongoConverter converter =new MappingMongoConverter(new DefaultDbRefResolver(factory), mongoMappingContext);
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));

        return converter;
    }

}
